<?php

namespace Apps\AppApi\Method\User;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\UserAttribute;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\UserBase;
use Apps\Common\Models\UserFollow;
use Apps\Common\Libs\PicUrl;

/**
 * 专家列表（用户没有关注的）
 */
class ExpertList extends BaseMethod
{
    public function run()
    {
    	$user_id = intval($this->getDataItem('user_id', 0));
    	$page = intval($this->getDataItem('page', 1));

		$limit = $this->getConfig()->limit;
		$offset = ($page - 1) * $limit;

//		$user_id = 12;

		$where = 'user_expert = 1 and user_state = 1';
		if ($user_id > 0) {
			// 用户关注的专家列表
			$followExpert = UserFollow::query()->where("user_id = {$user_id} and type = 2")->execute()->toArray();
			$expert = '';
			foreach ($followExpert as $val) {
				$expert .= $val['to_user_id'] . ',';
			}
			if ($expert && ($expert = trim($expert, ','))) {
				$where = "user_expert = 1 and user_state = 1 and user_id not in($expert)";
			}
		}
		$list = UserBase::query()->columns([
			'user_id',
			'user_nickname',
			'user_cover',
			'expert_follow_count',
		])->where($where)->orderBy('expert_follow_count DESC')->limit($limit, $offset)->execute()->toArray();

		foreach ($list as $k => $val) {
			$list[$k]['user_cover'] = PicUrl::ActivityCover($val['user_cover'], $this->getDi());

			// 获取专家的扩展信息
			if ($userAttribute = UserAttribute::findFirst('attr_type = 103 and attr_state = 1 and user_id = ' . $val['user_id'])) {
				$attr_value_json = $userAttribute->attr_value_json;
			} else {
				$attr_value_json = [];
			}
			$info = $attr_value_json ? json_decode($attr_value_json) : [];
			$list[$k]['experience'] = $info->experience ?: '0'; // 从业经验
			$list[$k]['experttitle'] = $info->experttitle ?: ''; // 擅长领域
			$list[$k]['field'] = $info->field ?: ''; // 专家头衔(array)
		}

		$this->setResult($list);
    }

	/*$list = UserBase::query()->columns([
			'\Apps\Common\Models\UserBase.user_id',
			'user_nickname',
			'user_cover',
			'expert_follow_count',
			'a.attr_value_json'
		])->leftJoin('\Apps\Common\Models\UserAttribute', 'a.user_id = \Apps\Common\Models\UserBase.user_id', 'a')->where($where)->orderBy('expert_follow_count DESC')->limit($limit, $offset)->execute()->toArray();

		foreach ($list as $k => $val) {
			$list[$k]['user_cover'] = PicUrl::ActivityCover($val['user_cover'], $this->getDi());

			// 组合专家的扩展信息
			$info = json_decode($val['attr_value_json']);
			$list[$k]['experience'] = $info->experience; // 从业经验
			$list[$k]['experttitle'] = $info->experttitle; // 擅长领域
			$list[$k]['field'] = $info->field; // 专家头衔(array)

			unset($list[$k]['attr_value_json']);
		}

		$this->setResult($list);*/
}